package com.clz.servlet;

import com.clz.entiy.User;
import com.clz.servise.Impl.UserServiceImpl;
import com.clz.servise.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/PageServlet")
public class PageServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 处理POST请求的逻辑
        String keyword = request.getParameter("keyword");
        if (keyword == null) {
            keyword = "";
        }
        String currPage = request.getParameter("pageIndex");
        if (currPage == null) {
            currPage = "1";
        }
        int pageIndex = Integer.parseInt(currPage);
        UserService userService = new UserServiceImpl();

        int count = userService.selectUserCount();
        int totalPages = userService.getTotalPages(count, UserServiceImpl.PAGE_SIZE);

        if (pageIndex < 1) {
            pageIndex = 1;
        } else if (pageIndex > totalPages) {
            pageIndex = totalPages;
        }

        List<User> list = userService.Paging(pageIndex, UserServiceImpl.PAGE_SIZE, keyword);
        request.setAttribute("keyword", keyword);
        request.setAttribute("pageIndex", pageIndex);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("list", list);

        request.getRequestDispatcher("Page.jsp").forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
